// profile.js
const app = getApp();
const storage = require('../../utils/storage.js');
const api = require('../../utils/api.js');

Page({
  data: {
    userInfo: null,
    hasUserInfo: false,
    favorites: [],
    playHistory: [],
    currentTab: 'favorite', // favorite or history
    currentMusic: null,
    isPlaying: false
  },

  onLoad() {
    this.checkUserInfo();
  },

  onShow() {
    if (this.data.hasUserInfo) {
      this.loadUserData();
    }
    this.updatePlayStatus();
  },

  // 检查用户信息
  checkUserInfo() {
    const userInfo = storage.getUserInfo();
    if (userInfo) {
      this.setData({
        userInfo,
        hasUserInfo: true
      });
      this.loadUserData();
    }
  },

  // 加载用户数据
  loadUserData() {
    const favorites = storage.getFavorites();
    const playHistory = storage.getPlayHistory();
    
    this.setData({
      favorites,
      playHistory
    });
  },

  // 用户登录
  getUserProfile() {
    wx.getUserProfile({
      desc: '用于完善用户资料',
      success: (res) => {
        const userInfo = res.userInfo;
        
        // 获取微信登录凭证
        wx.login({
          success: (loginRes) => {
            if (loginRes.code) {
              // 构建用户信息对象
              const userData = {
                username: userInfo.nickName || 'user_' + Date.now(),
                nickname: userInfo.nickName,
                avator: userInfo.avatarUrl,
                sex: userInfo.gender === 1 ? 1 : 0,
                location: userInfo.country + ' ' + userInfo.province + ' ' + userInfo.city,
                openid: loginRes.code // 实际应用中需要通过后端用code换取openid
              };
              
              // 保存用户信息到数据库
              this.saveUserToDatabase(userData, userInfo);
            } else {
              console.log('获取登录凭证失败：' + loginRes.errMsg);
              // 即使没有获取到code，也保存到本地
              this.saveUserLocally(userInfo);
            }
          },
          fail: () => {
            // 登录失败，仅保存到本地
            this.saveUserLocally(userInfo);
          }
        });
      },
      fail: () => {
        wx.showToast({
          title: '登录失败',
          icon: 'none'
        });
      }
    });
  },

  // 保存用户信息到数据库
  saveUserToDatabase(userData, userInfo) {
    api.saveUserInfo(userData).then(res => {
      console.log('用户信息已保存到数据库：', res);
      
      // 保存用户ID
      if (res && res.id) {
        userInfo.userId = res.id;
      }
      
      // 同时保存到本地存储
      storage.saveUserInfo(userInfo);
      app.globalData.userInfo = userInfo;
      
      this.setData({
        userInfo,
        hasUserInfo: true
      });
      
      this.loadUserData();
      
      wx.showToast({
        title: '登录成功',
        icon: 'success'
      });
    }).catch(err => {
      console.error('保存用户信息到数据库失败：', err);
      
      // 即使保存到数据库失败，也保存到本地
      this.saveUserLocally(userInfo);
    });
  },

  // 仅保存到本地
  saveUserLocally(userInfo) {
    storage.saveUserInfo(userInfo);
    app.globalData.userInfo = userInfo;
    
    this.setData({
      userInfo,
      hasUserInfo: true
    });
    
    this.loadUserData();
    
    wx.showToast({
      title: '登录成功',
      icon: 'success'
    });
  },

  // 退出登录
  logout() {
    wx.showModal({
      title: '提示',
      content: '确定要退出登录吗？',
      success: (res) => {
        if (res.confirm) {
          storage.clearUserInfo();
          app.globalData.userInfo = null;
          
          this.setData({
            userInfo: null,
            hasUserInfo: false,
            favorites: [],
            playHistory: []
          });
          
          wx.showToast({
            title: '已退出登录',
            icon: 'success'
          });
        }
      }
    });
  },

  // 切换标签
  switchTab(e) {
    const tab = e.currentTarget.dataset.tab;
    this.setData({ currentTab: tab });
  },

  // 播放音乐
  playMusic(e) {
    const type = e.currentTarget.dataset.type;
    const index = e.currentTarget.dataset.index;
    
    let music;
    let playlist;
    
    if (type === 'favorite') {
      music = this.data.favorites[index];
      playlist = this.data.favorites;
    } else {
      music = this.data.playHistory[index];
      playlist = this.data.playHistory;
    }
    
    if (!music) return;
    
    app.globalData.currentMusic = music;
    app.globalData.playlist = playlist;
    app.globalData.playIndex = index;
    
    storage.addPlayHistory(music);
    
    const audioManager = app.globalData.audioManager;
    audioManager.title = music.title;
    audioManager.singer = music.singer;
    audioManager.coverImgUrl = music.coverImgUrl;
    audioManager.src = music.src;
    
    this.setData({
      currentMusic: music,
      isPlaying: true
    });
  },

  // 取消收藏
  removeFavorite(e) {
    const index = e.currentTarget.dataset.index;
    const music = this.data.favorites[index];
    
    wx.showModal({
      title: '提示',
      content: '确定要取消收藏吗？',
      success: (res) => {
        if (res.confirm) {
          storage.removeFavorite(music.id);
          this.loadUserData();
          
          wx.showToast({
            title: '已取消收藏',
            icon: 'success'
          });
        }
      }
    });
  },

  // 清空播放历史
  clearHistory() {
    wx.showModal({
      title: '提示',
      content: '确定要清空播放历史吗？',
      success: (res) => {
        if (res.confirm) {
          storage.clearPlayHistory();
          this.loadUserData();
          
          wx.showToast({
            title: '已清空',
            icon: 'success'
          });
        }
      }
    });
  },

  // 更新播放状态
  updatePlayStatus() {
    const currentMusic = app.globalData.currentMusic;
    const audioManager = app.globalData.audioManager;
    
    if (currentMusic) {
      this.setData({
        currentMusic,
        isPlaying: !audioManager.paused
      });
    }
  },

  // 切换播放/暂停
  togglePlay() {
    const audioManager = app.globalData.audioManager;
    
    if (!this.data.currentMusic) return;
    
    if (this.data.isPlaying) {
      audioManager.pause();
      this.setData({ isPlaying: false });
    } else {
      audioManager.play();
      this.setData({ isPlaying: true });
    }
  },

  // 播放下一首
  playNext() {
    const playlist = app.globalData.playlist;
    const currentIndex = app.globalData.playIndex;
    
    if (!playlist || playlist.length === 0) return;
    
    const nextIndex = (currentIndex + 1) % playlist.length;
    const nextMusic = playlist[nextIndex];
    
    app.globalData.currentMusic = nextMusic;
    app.globalData.playIndex = nextIndex;
    
    storage.addPlayHistory(nextMusic);
    
    const audioManager = app.globalData.audioManager;
    audioManager.title = nextMusic.title;
    audioManager.singer = nextMusic.singer;
    audioManager.coverImgUrl = nextMusic.coverImgUrl;
    audioManager.src = nextMusic.src;
    
    this.setData({
      currentMusic: nextMusic,
      isPlaying: true
    });
  },

  // 跳转到播放器
  goToPlayer() {
    if (this.data.currentMusic) {
      wx.navigateTo({
        url: '/pages/player/player'
      });
    }
  }
});
